package project.youkumenu.customview;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;

/**
 * Created by lgs on 2018/3/7.
 */

public class GameView extends View implements Runnable {

    private Paint mPaint;   //绘制矩形的画笔
    private Rect rect;

    private int width;
    private int height;

    public GameView(Context context) {
        this(context, null);
    }

    public GameView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public GameView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {

        width = getMeasuredWidth();
        height = getMeasuredHeight();
        Log.i("aaa", "width = " + width + ", height = " + height);

        /* 构建对象 */
        mPaint = new Paint();
        /* 设置取消锯齿效果 */
        mPaint.setAntiAlias(true);

        rect = new Rect(150, 75, 1080, 1920);

         /* 开启线程 */
        new Thread().start();
    }

    @Override
    public void run() {
        while (!Thread.currentThread().isInterrupted()) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
            /*invalidate()得在UI线程中被调动，在工作者线程中可以通过Handler来通知UI线程进行界面更新。
                而postInvalidate()在工作者线程中被调用*/

            // 使用postInvalidate则比较简单，不需要handler，直接在线程中调用postInvalidate即可
            postInvalidate();
            //            invalidate();
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        /* 设置画布的颜色 */
        canvas.drawColor(Color.DKGRAY);

        /* 设置裁剪区域 */
        canvas.clipRect(10, 10, 280, 260);

        /* 线锁定画布 */
        canvas.save();

        /* 旋转画布 */
        canvas.rotate(45.0f);

        mPaint.setColor(Color.RED);
        canvas.drawRect(15, 15, 140, 70, mPaint);

         /* 解除画布的锁定 */
        canvas.restore();

        /* 设置颜色及绘制另一个矩形 */
        mPaint.setColor(Color.GREEN);
        canvas.drawRect(rect, mPaint);
    }

    // 触笔事件(影响监听事件)
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return super.onTouchEvent(event);
    }

    // 按键按下事件
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return true;
    }

    // 按键弹起事件
    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        return false;
    }

    @Override
    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
        return true;
    }

}
